/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework.autoproxy;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.Advisor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Helper for retrieving standard Spring Advisors from a BeanFactory,
 * for use with auto-proxying.
 *
 * @author Juergen Hoeller
 * @since 2.0.2
 * @see AbstractAdvisorAutoProxyCreator
 */
public class BeanFactoryAdvisorRetrievalHelper {

	private static final Log logger = LogFactory.getLog(BeanFactoryAdvisorRetrievalHelper.class);

	private final ConfigurableListableBeanFactory beanFactory;

	@Nullable
	private volatile String[] cachedAdvisorBeanNames;


	/**
	 * Create a new BeanFactoryAdvisorRetrievalHelper for the given BeanFactory.
	 * @param beanFactory the ListableBeanFactory to scan
	 */
	public BeanFactoryAdvisorRetrievalHelper(ConfigurableListableBeanFactory beanFactory) {
		Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
		this.beanFactory = beanFactory;
	}


	/**
	 * 寻找当前 BeanFactory 中所有符合条件的 Advisor bean，并返回列表。
	 * 会缓存已经找到的 Advisor bean 名称，避免重复查找。
	 *
	 * Find all eligible Advisor beans in the current bean factory,
	 * ignoring FactoryBeans and excluding beans that are currently in creation.
	 * @return the list of {@link org.springframework.aop.Advisor} beans
	 * @see #isEligibleBean
	 */
	public List<Advisor> findAdvisorBeans() {
		// 获取缓存的 Advisor bean 名称
		// Determine list of advisor bean names, if not cached already.
		String[] advisorNames = this.cachedAdvisorBeanNames;

		if (advisorNames == null) {
			// 如果缓存为空，则从 BeanFactory 中查找所有实现了 Advisor 接口的 bean 名称
			// 第三个参数 true：包括祖先 BeanFactory 中的 bean
			// 第四个参数 false：不要初始化 FactoryBean
			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the auto-proxy creator apply to them!
			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					this.beanFactory, Advisor.class, true, false);
			// 缓存起来，下次直接使用
			this.cachedAdvisorBeanNames = advisorNames;
		}

		// 如果没有找到任何 Advisor bean，返回空列表
		if (advisorNames.length == 0) {
			return new ArrayList<>();
		}

		// 用于保存最终符合条件的 Advisor 实例
		List<Advisor> advisors = new ArrayList<>();

		// 遍历所有找到的 Advisor bean 名称
		for (String name : advisorNames) {
			// isEligibleBean 提供了一个 hook，子类可以重写用来过滤不想处理的 Advisor
			if (isEligibleBean(name)) {
				// 如果当前 Advisor bean 正在创建中，跳过，避免循环依赖
				if (this.beanFactory.isCurrentlyInCreation(name)) {
					if (logger.isTraceEnabled()) {
						logger.trace("Skipping currently created advisor '" + name + "'");
					}
				}
				else {
					try {
						// ********** 核心方法： ************
						// 通过 beanName 从容器中获取对应的 Advisor 实例，并加入到结果列表。
						// Advisor 是 Spring AOP 中的“通知器”，它本质上是 Advice（增强逻辑） + Pointcut（匹配规则）的组合。
						// 一个 Advisor 主要由两个组成在一起的：
						//   1. *在哪些方法上应用增强*（由 Pointcut 决定）
						//   2. *具体要执行什么增强逻辑*（由 Advice 决定，如 BeforeAdvice、AfterReturningAdvice 等）
						//
						// 调用 getBean(name, Advisor.class) 会：
						//   - 从 BeanFactory 中取出名为 name 的 Advisor 对象；
						//   - 若该 bean 尚未实例化，会在此处触发完整的 Spring bean 创建流程；
						//   - 最终得到一个可用于 AOP 自动代理构建的 Advisor 实例。
						//
						// 将获取到的 Advisor 放入 advisors 列表，供后续 AOP 代理创建使用。
						advisors.add(this.beanFactory.getBean(name, Advisor.class));
					}
					catch (BeanCreationException ex) {
						// 捕获 Bean 创建异常，检查是否是循环依赖导致
						Throwable rootCause = ex.getMostSpecificCause();
						if (rootCause instanceof BeanCurrentlyInCreationException) {
							BeanCreationException bce = (BeanCreationException) rootCause;
							String bceBeanName = bce.getBeanName();
							// 如果依赖的 bean 正在创建中，则跳过该 Advisor
							if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
								if (logger.isTraceEnabled()) {
									logger.trace("Skipping advisor '" + name +
											"' with dependency on currently created bean: " + ex.getMessage());
								}
								// 忽略该 Advisor，继续处理其他 Advisor
								// Ignore: indicates a reference back to the bean we're trying to advise.
								// We want to find advisors other than the currently created bean itself.
								continue;
							}
						}
						// 非循环依赖异常，直接抛出
						throw ex;
					}
				}
			}
		}

		// 返回最终符合条件的 Advisor 列表
		return advisors;
	}

	/**
	 * Determine whether the aspect bean with the given name is eligible.
	 * <p>The default implementation always returns {@code true}.
	 * @param beanName the name of the aspect bean
	 * @return whether the bean is eligible
	 */
	protected boolean isEligibleBean(String beanName) {
		return true;
	}

}
